package com.control.qct.businesssteward.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.control.qct.businesssteward.R;
import com.control.qct.businesssteward.activity.GoodsActivity;
import com.control.qct.businesssteward.activity.GoodsBrandsActivity;
import com.control.qct.businesssteward.activity.GoodsSubUnitsActivity;
import com.control.qct.businesssteward.activity.GoodsSupplierActivity;
import com.control.qct.businesssteward.activity.GoodsTypeActivity;
import com.control.qct.businesssteward.activity.PhotoViewPagerActivity;
import com.control.qct.businesssteward.adapter.GoodsDetailPictureAdapter;
import com.control.qct.businesssteward.base.BaseBean;
import com.control.qct.businesssteward.base.BaseFragment;
import com.control.qct.businesssteward.httputils.HttpUtils;
import com.control.qct.businesssteward.model.GoodsDetailModel;
import com.control.qct.businesssteward.model.GoodsModel;
import com.control.qct.businesssteward.utils.DecimalFormatUtils;
import com.control.qct.businesssteward.utils.EditTextUtils;
import com.control.qct.businesssteward.utils.GlideUtil;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;

/**
 * 商品详情
 * Created by Administrator on 2017/12/18 0018.
 */

@SuppressLint("ValidFragment")
public class GoodsDetailFragment extends BaseFragment {
    @BindView(R.id.nsv_goods_detail)
    NestedScrollView mNsvGoodsDetail;
    @BindView(R.id.rl_goods_information)
    RelativeLayout mRlGoodsInformation;//商品显示
    @BindView(R.id.ll_system_code)
    LinearLayout mLlSystemCode;//系统编码
    @BindView(R.id.ll_line)
    LinearLayout mLlLine;//系统编码
    @BindView(R.id.ll_inventory)
    LinearLayout mLlInventory;//库存
    @BindView(R.id.iv_goods_picture)
    ImageView mIvGoodsPicture;//商品图片
    @BindView(R.id.tv_goods_name)
    TextView mTvGoodsName;//商品名称
    @BindView(R.id.tv_goods_barcode)
    TextView mTvGoodsBarcode;//商品编码
    @BindView(R.id.tv_goods_type)
    TextView mTvGoodsType;//商品品类
    @BindView(R.id.tv_goods_price)
    TextView mTvGoodsPrice;//商品价格
    @BindView(R.id.ib_add_picture)
    ImageButton mIbAddPicture;//添加商品图片
    @BindView(R.id.rv_goods_picture)
    RecyclerView mRvGoodsPicture;//添加的商品图片显示列表
    @BindView(R.id.et_main_code)
    EditText mEtMainCode;//主条码
    @BindView(R.id.et_storage_code)
    EditText mEtStorageCode;//主条码
    @BindView(R.id.et_goods_full_name)
    EditText mEtGoodsFullName;//商品全称
    @BindView(R.id.tv_type)
    TextView mTvType;//品类
    @BindView(R.id.tv_brand)
    TextView mTvBrand;//品牌
    @BindView(R.id.tv_measure_small_unit)
    TextView mTvMeasureSmallUnit;//计量小单位
    @BindView(R.id.rb_record_num)
    RadioButton mRbRecordNum;//计件
    @BindView(R.id.rb_weigh)
    RadioButton mRbWeigh;//称重
    @BindView(R.id.rg_valuation_style)
    RadioGroup mRgValuationStyle;//计价方式
    @BindView(R.id.et_system_code)
    EditText mEtSystemCode;//系统编码
    @BindView(R.id.tv_main_supplier)
    TextView mTvMainSupplier;//主供应商
    @BindView(R.id.et_inventory)
    EditText mEtInventory;//库存
    @BindView(R.id.et_inventory_warning_up)
    EditText mEtInventoryWarningUp;//库存预警上限
    @BindView(R.id.et_inventory_warning_down)
    EditText mEtInventoryWarningDown;//库存预警下限
    @BindView(R.id.et_specification)
    EditText mEtSpecification;//规格
    @BindView(R.id.et_carton_specification)
    EditText mEtCartonSpecification;//箱规
    @BindView(R.id.et_manufacturer)
    EditText mEtManufacturer;//生产厂家
    @BindView(R.id.et_expiration_date)
    EditText mEtExpirationDate;//保质期
    @BindView(R.id.rb_day)
    RadioButton mRbDay;//天
    @BindView(R.id.rb_month)
    RadioButton mRbMonth;//月
    @BindView(R.id.rb_year)
    RadioButton mRbYear;//年
    @BindView(R.id.rg_expiration_date_unit)
    RadioGroup mRgExpirationDateUnit;//保质期单位
    @BindView(R.id.et_expiration_date_warning)
    EditText mEtExpirationDateWarning;//保质期预警天数
    @BindView(R.id.et_system_selling)
    EditText mEtSystemSelling;//系统售价
    @BindView(R.id.et_wholesale_selling)
    EditText mEtWholesaleSelling;//批发价
    @BindView(R.id.et_join_selling)
    EditText mEtJoinSelling;//加盟价
    @BindView(R.id.et_stock_selling)
    EditText mEtStockSelling;//进价
    @BindView(R.id.et_stock_selling_tax)
    EditText mEtStockSellingTax;//进价税率
    @BindView(R.id.et_sale_tax)
    EditText mEtSaleTax;//销售税率
    @BindView(R.id.et_member_selling)
    EditText mEtMemberSelling;//会员价
    @BindView(R.id.et_member_selling1)
    EditText mEtMemberSelling1;//会员价1
    @BindView(R.id.et_member_selling2)
    EditText mEtMemberSelling2;//会员价2
    @BindView(R.id.et_member_selling3)
    EditText mEtMemberSelling3;//会员价3
    @BindView(R.id.et_member_selling4)
    EditText mEtMemberSelling4;//会员价4
    @BindView(R.id.et_member_selling5)
    EditText mEtMemberSelling5;//会员价5
    @BindView(R.id.rb_order_tag_allow)
    RadioButton mRbOrderTagAllow;//订货标志 -- 允许
    @BindView(R.id.rb_order_tag_not_allow)//订货标志 -- 不允许
            RadioButton mRbOrderTagNotAllow;
    @BindView(R.id.rg_order_tag)
    RadioGroup mRgOrderTag;//订货标志
    @BindView(R.id.rb_front_adjust_price_allow)
    RadioButton mRbFrontAdjustPriceAllow;//前台调价 -- 允许
    @BindView(R.id.rb_front_adjust_price_not_allow)
    RadioButton mRbFrontAdjustPriceNotAllow;//前台调价 -- 不允许
    @BindView(R.id.rg_front_adjust_price)
    RadioGroup mRgFrontAdjustPrice;//前台调价
    @BindView(R.id.rb_return_goods_tag_allow)
    RadioButton mRbReturnGoodsTagAllow;//退货标志 -- 允许
    @BindView(R.id.rb_return_goods_tag_not_allow)
    RadioButton mRbReturnGoodsTagNotAllow;//退货标志 -- 不允许
    @BindView(R.id.rg_return_goods_tag)
    RadioGroup mRgReturnGoodsTag;//退货标志
    @BindView(R.id.tv_delete_goods)
    TextView mTvDeleteGoods;//删除商品
    @BindView(R.id.tv_put_away_or_sold_out)
    TextView mTvPutAwayOrSoldOut;//上架或下架


    private GoodsActivity mGoodsActivity;
    private static final int REQUEST_PHOTO_CHOOSE = 0x1001; //选择照片
    private static final int REQUEST_GOODS_TYPE_CHOOSE = 0x1002;//品类选择
    private static final int REQUEST_GOODS_BRAND_CHOOSE = 0x1003;//品牌选择
    private static final int REQUEST_MEASURE_UNIT_CHOOSE = 0x1004;//单位选择
    private static final int REQUEST_MAIN_SUPPLIER_CHOOSE = 0x1005;//主供应商选择


    private GoodsDetailPictureAdapter mGoodsDetailPictureAdapter;
    private ArrayList<GoodsDetailModel.FileImageUrl> mPhotos = new ArrayList<>();//选择的图片地址集合
    private ArrayList<String> mFileList = new ArrayList<>();//选择的图片地址集合--区分是否手动添加的图片而不是后台返回的
    private int photoCount;//设置最多显示的图片个数
    private boolean isShow;
    private Bundle mBundle;
    private int mId;
    private GoodsModel.DatasBean mGoodsModel;
    private IChangeGoodsStatus mIChangeGoodsStatus;
    private Map<String, String> mParams;//请求参数

    private int mGoodId;
    private int mGoodsState;
    private int mCategorySN;//品类id
    private int mBrandSN;//品牌id
    private int mDicSN;//计量最小单位id
    private String mSupplierId;//供应商id
    private double mBuyPrice;
    private double mTradePrice;
    private double mSysPrice;
    private double mJoinPrice;
    private double mMemberPrice;
    private double mMemberPrice1;
    private double mMemberPrice2;
    private double mMemberPrice3;
    private double mMemberPrice4;
    private double mMemberPrice5;
    private double mStockRate;
    private double mSaleRate;
    private int mFavorable = 1;//前台优惠（1:允许调价、0:不允许调价)
    private int mExpiry = 0;//保质期（0:不限） [默认值：((0))]
    private int mExpiryUnit = 1;//保质期单位（1:天、2:月、3:年)
    private int mValuationType = 1;//计价方式（1:计件、2:称重）
    private int mIsReturnSale = 1;//退货标志（1:允许、0:不允许）
    private int mIsAcceptOrder = 1;//订货标志（1:允许、0:不允许）


    @Override
    protected View initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        return inflater.inflate(R.layout.fragment_goods_detail, container, false);
    }

    @SuppressLint("ValidFragment")
    public GoodsDetailFragment(int id, IChangeGoodsStatus iChangeGoodsStatus) {
        this.mId = id;
        this.mIChangeGoodsStatus = iChangeGoodsStatus;
    }

    public GoodsDetailFragment(int id, GoodsModel.DatasBean goodsModel, IChangeGoodsStatus iChangeGoodsStatus) {
        this.mId = id;
        this.mGoodsModel = goodsModel;
        this.mIChangeGoodsStatus = iChangeGoodsStatus;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mGoodsActivity = (GoodsActivity) context;
    }

    @Override
    protected void initView(View view) {
        mGoodsActivity.setLeftIcon(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mGoodsActivity.getSupportFragmentManager().popBackStack();
            }
        });

        mRvGoodsPicture.setLayoutManager(new LinearLayoutManager(mGoodsActivity, LinearLayoutManager.HORIZONTAL,
                false));
        mGoodsDetailPictureAdapter = new GoodsDetailPictureAdapter(mPhotos);
        mRvGoodsPicture.setAdapter(mGoodsDetailPictureAdapter);
        if (mId == 1) { //新增
            mRlGoodsInformation.setVisibility(View.GONE);
            mLlInventory.setVisibility(View.GONE);
            mLlSystemCode.setVisibility(View.GONE);
            mLlLine.setVisibility(View.GONE);
            mGoodsActivity.setRightIcon("取消", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mGoodsActivity.getSupportFragmentManager().popBackStack();
                }
            });
            mTvDeleteGoods.setText("保存为草稿");
            mTvPutAwayOrSoldOut.setText("保存并上架");
            if (mGoodsDetailPictureAdapter != null) {
                mGoodsDetailPictureAdapter.setShow(true);
            }
        } else if (mId == 2) {//查看商品详情
            setIsEnable(false);
            mGoodsActivity.setRightIcon("编辑", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isShow) {
                        isShow = false;
                        mGoodsActivity.setRightTitle("编辑");
                        addOrUpdateProduct(mGoodId + "", mGoodsState + "");
                    } else {
                        isShow = true;
                        mGoodsActivity.setRightTitle("完成");
                    }
                    setIsEnable(isShow);
                    if (mGoodsDetailPictureAdapter != null) {
                        mGoodsDetailPictureAdapter.setShow(isShow);
                    }
                }
            });
            //显示传进来的商品信息
            GlideUtil.loadImage(this, mGoodsModel.getImageBigUrl(), mIvGoodsPicture);
            mTvGoodsName.setText(mGoodsModel.getTitle());
            mTvGoodsBarcode.setText(mGoodsModel.getBarcode());
            mTvGoodsType.setText(mGoodsModel.getCategoryTitle());
            mTvGoodsPrice.setText("￥" + DecimalFormatUtils.DecimalFormatTwo(mGoodsModel.getSysPrice()));
            //联网获取商品详情信息
            getGoodsDetail();
        }
        //点击图片放大
        mGoodsDetailPictureAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mBundle = new Bundle();
                mBundle.putInt("photoId", position);
                mBundle.putSerializable("photo_address", mPhotos);
                startActivity(PhotoViewPagerActivity.class, mBundle);
            }
        });
        //删除图片--判断是删除本地图片还是后台删除后台返回的图片
        mGoodsDetailPictureAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
                if (mFileList.size() > 0) {
                    if (mFileList.contains(((List<GoodsDetailModel.FileImageUrl>) adapter.getData()).get(position)
                            .getImageBigUrl())) {
                        mFileList.remove(((List<GoodsDetailModel.FileImageUrl>) adapter.getData()).get(position)
                                .getImageBigUrl());
                        ((List<GoodsDetailModel.FileImageUrl>) adapter.getData()).remove(position);
                        photoCount--;
                        mGoodsDetailPictureAdapter.notifyDataSetChanged();
                    } else {
                        removeProductImage(adapter, position);
                    }
                } else {
                    removeProductImage(adapter, position);
                }
            }
        });
    }

    /**
     * 删除图片
     *
     * @param adapter
     * @param position
     */
    private void removeProductImage(final BaseQuickAdapter adapter, final int position) {
        mNetProtocol.removeProductImage(activity, mGoodId, ((List<GoodsDetailModel.FileImageUrl>) adapter.getData())
                .get(position).getFileName(), new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                ((List<GoodsDetailModel.FileImageUrl>) adapter.getData()).remove(position);
                photoCount--;
                mGoodsDetailPictureAdapter.notifyDataSetChanged();
                showShortToast("图片已删除！");
            }

            @Override
            public void onFail(BaseBean baseBean) {

            }
        });
    }

    /**
     * 设置请求参数的值
     *
     * @param goodsDetailModel
     */
    private void setParams(GoodsDetailModel goodsDetailModel) {
        mGoodId = goodsDetailModel.getId();
        mGoodsState = goodsDetailModel.getState();
        mCategorySN = goodsDetailModel.getCategorySN();
        mBrandSN = goodsDetailModel.getBrandSN();
        mDicSN = goodsDetailModel.getSubUnitId();
        mSupplierId = goodsDetailModel.getSupplierId();
        mBuyPrice = goodsDetailModel.getBuyPrice();
        mTradePrice = goodsDetailModel.getTradePrice();
        mSysPrice = goodsDetailModel.getSysPrice();
        mJoinPrice = goodsDetailModel.getJoinPrice();
        mMemberPrice = goodsDetailModel.getMemberPrice();
        mMemberPrice1 = goodsDetailModel.getMemberPrice1();
        mMemberPrice2 = goodsDetailModel.getMemberPrice2();
        mMemberPrice3 = goodsDetailModel.getMemberPrice3();
        mMemberPrice4 = goodsDetailModel.getMemberPrice4();
        mMemberPrice5 = goodsDetailModel.getMemberPrice5();
        mStockRate = goodsDetailModel.getStockRate();
        mSaleRate = goodsDetailModel.getSaleRate();
        mFavorable = goodsDetailModel.getFavorable();
        mExpiry = goodsDetailModel.getExpiry();
        mExpiryUnit = goodsDetailModel.getExpiryUnit();
        mValuationType = goodsDetailModel.getValuationType();
        mIsReturnSale = goodsDetailModel.getIsReturnSale();
        mIsAcceptOrder = goodsDetailModel.getIsAcceptOrder();
    }


    @OnClick({R.id.ib_add_picture, R.id.tv_type, R.id.tv_brand, R.id.tv_measure_small_unit, R.id.tv_main_supplier, R
            .id.tv_delete_goods, R.id.tv_put_away_or_sold_out, R.id.rb_record_num, R.id.rb_weigh, R.id.rb_day, R.id
            .rb_month, R.id.rb_year, R.id.rb_order_tag_allow, R
            .id.rb_order_tag_not_allow, R.id.rb_front_adjust_price_allow, R.id.rb_front_adjust_price_not_allow, R.id
            .rb_return_goods_tag_allow, R.id.rb_return_goods_tag_not_allow})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_add_picture://添加商品图片
                Album.image(this) // 选择图片。
                        .multipleChoice()//多选模式，单选模式为：singleChoice()。
                        .widget(Widget.newDarkBuilder(activity)//自定义UI
                                .statusBarColor(Color.parseColor("#05C1AB"))
                                .toolBarColor(Color.parseColor("#05C1AB"))
                                .mediaItemCheckSelector(Color.WHITE, Color.parseColor("#05C1AB"))
                                .bucketItemCheckSelector(Color.RED, Color.YELLOW)
                                .build())
                        .requestCode(REQUEST_PHOTO_CHOOSE)//请求码，会在listener中返回。
                        .camera(true)// 是否显示相机.
                        .columnCount(3)//页面列表的列数。
                        .selectCount(5)//最多选择几张图片
                        .onResult(new Action<ArrayList<AlbumFile>>() {
                            @Override
                            public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                                photoCount += result.size();
                                if (photoCount > 5) {
                                    photoCount -= result.size();
                                    showShortToast("最多只能显示五张！");
                                    return;
                                }
                                for (int i = 0; i < result.size(); i++) {
                                    mPhotos.add(new GoodsDetailModel.FileImageUrl(result.get(i).getThumbPath(), ""));
                                    mFileList.add(result.get(i).getThumbPath());
                                }
                                if (mGoodsDetailPictureAdapter != null) {
                                    mGoodsDetailPictureAdapter.notifyDataSetChanged();
                                }
                            }
                        })
                        .start();
                break;
            case R.id.tv_type://品类
                Bundle bundle = new Bundle();
                bundle.putInt("id", 2);
                bundle.putString("value", mTvType.getText().toString());
                bundle.putInt("categorySN", mCategorySN);
                startActivityForResult(GoodsTypeActivity.class, REQUEST_GOODS_TYPE_CHOOSE, bundle);
                break;
            case R.id.tv_brand://品牌
                mBundle = new Bundle();
                if (!TextUtils.isEmpty(mTvBrand.getText().toString())) {
                    mBundle.putInt("brandSN", mBrandSN);
                }
                startActivityForResult(GoodsBrandsActivity.class, REQUEST_GOODS_BRAND_CHOOSE, mBundle);
                break;
            case R.id.tv_measure_small_unit://计量小单位
                mBundle = new Bundle();
                if (!TextUtils.isEmpty(mTvMeasureSmallUnit.getText().toString())) {
                    mBundle.putInt("dicSN", mDicSN);
                }
                startActivityForResult(GoodsSubUnitsActivity.class, REQUEST_MEASURE_UNIT_CHOOSE, mBundle);
                break;
            case R.id.tv_main_supplier://主供应商
                mBundle = new Bundle();
                if (!TextUtils.isEmpty(mTvMainSupplier.getText().toString())) {
                    mBundle.putString("supplierId", mSupplierId);
                }
                startActivityForResult(GoodsSupplierActivity.class, REQUEST_MAIN_SUPPLIER_CHOOSE, mBundle);
                break;
            case R.id.rb_record_num://计件
                mValuationType = 1;
                break;
            case R.id.rb_weigh://称重
                mValuationType = 2;
                break;
            case R.id.rb_day://天
                mExpiryUnit = 1;
                break;
            case R.id.rb_month://月
                mExpiryUnit = 2;
                break;
            case R.id.rb_year://年
                mExpiryUnit = 3;
                break;
            case R.id.rb_order_tag_allow://订货标志-- 允许
                mIsAcceptOrder = 1;
                break;
            case R.id.rb_order_tag_not_allow://订货标志-- 不允许
                mIsAcceptOrder = 0;
                break;
            case R.id.rb_front_adjust_price_allow://前台调价-- 允许
                mFavorable = 1;
                break;
            case R.id.rb_front_adjust_price_not_allow://前台调价-- 不允许
                mFavorable = 0;
                break;
            case R.id.rb_return_goods_tag_allow://退货标志-- 允许
                mIsReturnSale = 1;
                break;
            case R.id.rb_return_goods_tag_not_allow://退货标志-- 不允许
                mIsReturnSale = 0;
                break;
            case R.id.tv_delete_goods:
                if (mId == 1) {//保存为草稿
                    addOrUpdateProduct("0", "0");
                } else {//删除商品
                    deleteGoods();
                }
                break;
            case R.id.tv_put_away_or_sold_out:
                if (mId == 1) {//保存并上架
                    addOrUpdateProduct("0", "1");
                } else {//上架或下架
                    setGoodsState();
                }
                break;
        }
    }

    /**
     * 设置是否可以编辑
     **/
    private void setIsEnable(boolean isClick) {
        mIbAddPicture.setClickable(isClick);
        mTvType.setClickable(isClick);
        mTvBrand.setClickable(isClick);
        mTvMeasureSmallUnit.setClickable(isClick);
        mRbRecordNum.setClickable(false);
        mRbWeigh.setClickable(false);
        mTvMainSupplier.setClickable(isClick);
        mRbDay.setClickable(isClick);
        mRbMonth.setClickable(isClick);
        mRbYear.setClickable(isClick);
        mRbOrderTagAllow.setClickable(isClick);
        mRbOrderTagNotAllow.setClickable(isClick);
        mRbFrontAdjustPriceAllow.setClickable(isClick);
        mRbFrontAdjustPriceNotAllow.setClickable(isClick);
        mRbReturnGoodsTagAllow.setClickable(isClick);
        mRbReturnGoodsTagNotAllow.setClickable(isClick);
        EditTextUtils.setIsEdit(mEtMainCode, isClick);
        EditTextUtils.setIsEdit(mEtStorageCode, isClick);
        EditTextUtils.setIsEdit(mEtGoodsFullName, isClick);
        EditTextUtils.setIsEdit(mEtCartonSpecification, isClick);
        EditTextUtils.setIsEdit(mEtExpirationDate, isClick);
        EditTextUtils.setIsEdit(mEtExpirationDateWarning, isClick);
        EditTextUtils.setIsEdit(mEtSystemCode, isClick);
        EditTextUtils.setIsEdit(mEtInventory, isClick);
        EditTextUtils.setIsEdit(mEtInventoryWarningUp, isClick);
        EditTextUtils.setIsEdit(mEtInventoryWarningDown, isClick);
        EditTextUtils.setIsEdit(mEtJoinSelling, isClick);
        EditTextUtils.setIsEdit(mEtManufacturer, isClick);
        EditTextUtils.setIsEdit(mEtStockSelling, isClick);
        EditTextUtils.setIsEdit(mEtMemberSelling1, isClick);
        EditTextUtils.setIsEdit(mEtMemberSelling2, isClick);
        EditTextUtils.setIsEdit(mEtMemberSelling3, isClick);
        EditTextUtils.setIsEdit(mEtMemberSelling4, isClick);
        EditTextUtils.setIsEdit(mEtSaleTax, isClick);
        EditTextUtils.setIsEdit(mEtSpecification, isClick);
        EditTextUtils.setIsEdit(mEtStockSellingTax, isClick);
        EditTextUtils.setIsEdit(mEtSystemSelling, isClick);
        EditTextUtils.setIsEdit(mEtWholesaleSelling, isClick);
    }

    /**
     * 获取商品详情
     */
    private void getGoodsDetail() {
        mNetProtocol.getGoodsDetail(activity, mGoodsModel.getId(), new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                GoodsDetailModel goodsDetailModel = (GoodsDetailModel) baseBean.getData();
                mPhotos.addAll(goodsDetailModel.getFileImageUrl());
                photoCount = mPhotos.size();
                if (mGoodsDetailPictureAdapter != null) {
                    mGoodsDetailPictureAdapter.notifyDataSetChanged();
                }
                setParams(goodsDetailModel);
                mEtMainCode.setText(goodsDetailModel.getBarcode());//主条码
                mEtStorageCode.setText(goodsDetailModel.getStorageCode());//主条码
                mEtGoodsFullName.setText(goodsDetailModel.getTitle());//商品全称
                mTvType.setText(goodsDetailModel.getCategoryTitle());//品类
                mTvBrand.setText(goodsDetailModel.getBrandTitle());//品牌
                mTvMeasureSmallUnit.setText(goodsDetailModel.getSubUnitTitle());//计量小单位
                mEtSystemCode.setText(goodsDetailModel.getProductCode());//系统编码
                mTvMainSupplier.setText(goodsDetailModel.getSupplierTitle());//主供应商
                mEtInventoryWarningUp.setText(goodsDetailModel.getInventoryWarningMax() + "");//库存预警上限
                mEtInventoryWarningDown.setText(goodsDetailModel.getInventoryWarning() + "");//库存预警下限
                mEtSpecification.setText(goodsDetailModel.getSize());//规格
                mEtCartonSpecification.setText(goodsDetailModel.getBoxBoard());//箱规
                mEtManufacturer.setText(goodsDetailModel.getFactory());//生产厂家
                mEtExpirationDate.setText(goodsDetailModel.getExpiry() == 0 ? "永久" : goodsDetailModel.getExpiry() + "");
                switch (goodsDetailModel.getExpiryUnit()) { //保质期单位
                    case 1:
                        mRgExpirationDateUnit.check(mRbDay.getId());
                        break;
                    case 2:
                        mRgExpirationDateUnit.check(mRbMonth.getId());
                        break;
                    case 3:
                        mRgExpirationDateUnit.check(mRbYear.getId());
                        break;
                }
                mEtExpirationDateWarning.setText(goodsDetailModel.getValidityWarning() + "");//保质期预警天数
                mEtSystemSelling.setText(DecimalFormatUtils.DecimalFormatTwo(goodsDetailModel.getSysPrice()));//系统售价
                mEtWholesaleSelling.setText(DecimalFormatUtils.DecimalFormatTwo(goodsDetailModel.getTradePrice()));//批发价
                mEtJoinSelling.setText(DecimalFormatUtils.DecimalFormatTwo(goodsDetailModel.getJoinPrice()));//加盟价
                mEtStockSelling.setText(DecimalFormatUtils.DecimalFormatTwo(goodsDetailModel.getBuyPrice()));//进价
                mEtStockSellingTax.setText(goodsDetailModel.getStockRate() + "");//进价税率
                mEtSaleTax.setText(goodsDetailModel.getSaleRate() + "");//进价税率
                mEtMemberSelling.setText(DecimalFormatUtils.DecimalFormatTwo(goodsDetailModel.getMemberPrice()));
                //会员价
                mEtMemberSelling1.setText(DecimalFormatUtils.DecimalFormatTwo(goodsDetailModel.getMemberPrice1()));
                //会员价1
                mEtMemberSelling2.setText(DecimalFormatUtils.DecimalFormatTwo(goodsDetailModel.getMemberPrice2()));
                //会员价2
                mEtMemberSelling3.setText(DecimalFormatUtils.DecimalFormatTwo(goodsDetailModel.getMemberPrice3()));
                //会员价3
                mEtMemberSelling4.setText(DecimalFormatUtils.DecimalFormatTwo(goodsDetailModel.getMemberPrice4()));
                //会员价4
                mEtMemberSelling5.setText(DecimalFormatUtils.DecimalFormatTwo(goodsDetailModel.getMemberPrice5()));
                //会员价5
                mRgValuationStyle.check(goodsDetailModel.getValuationType() == 1 ? mRbRecordNum.getId() : mRbWeigh
                        .getId());//计价方式
                mRgOrderTag.check(goodsDetailModel.getIsAcceptOrder() == 1 ? mRbOrderTagAllow.getId() :
                        mRbOrderTagNotAllow.getId());//订货标志
                mRgFrontAdjustPrice.check(goodsDetailModel.getFavorable() == 1 ? mRbFrontAdjustPriceAllow.getId() :
                        mRbFrontAdjustPriceNotAllow.getId());//前台调价
                mRgReturnGoodsTag.check(goodsDetailModel.getIsReturnSale() == 1 ? mRbReturnGoodsTagAllow.getId() :
                        mRbReturnGoodsTagNotAllow.getId());//退货标志
            }

            @Override
            public void onFail(BaseBean baseBean) {
                showShortToast(baseBean.getMessage());
            }
        });
    }

    /**
     * 删除商品
     */
    private void deleteGoods() {
        mNetProtocol.deleteGoods(activity, mGoodsModel.getId(), new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                showShortToast("删除成功!");
                mIChangeGoodsStatus.changeGoodsState(true);
                mGoodsActivity.getSupportFragmentManager().popBackStack();
            }

            @Override
            public void onFail(BaseBean baseBean) {
                showShortToast(baseBean.getMessage());
            }
        });
    }

    /**
     * 上架/下架
     */
    private void setGoodsState() {
        int state;
        if (mGoodsState == 1) {
            state = 2;
        } else {
            state = 1;
        }
        mNetProtocol.setGoodsState(activity, mGoodsModel.getId(), state, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                showShortToast("修改成功!");
                mIChangeGoodsStatus.changeGoodsState(true);
                mGoodsActivity.getSupportFragmentManager().popBackStack();
            }

            @Override
            public void onFail(BaseBean baseBean) {

            }
        });
    }

    /**
     * 回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
            switch (requestCode) {
                case REQUEST_GOODS_TYPE_CHOOSE://品类选择
                    mTvType.setText(data.getStringExtra("data"));
                    mCategorySN = data.getIntExtra("categorySN", -1);
                    break;
                case REQUEST_GOODS_BRAND_CHOOSE://品牌选择
                    mTvBrand.setText(data.getStringExtra("data"));
                    mBrandSN = data.getIntExtra("brandSN", -1);
                    break;
                case REQUEST_MEASURE_UNIT_CHOOSE://最小计量单位选择
                    mTvMeasureSmallUnit.setText(data.getStringExtra("data"));
                    mDicSN = data.getIntExtra("dicSN", -1);
                    break;
                case REQUEST_MAIN_SUPPLIER_CHOOSE://主供应商选择
                    mTvMainSupplier.setText(data.getStringExtra("data"));
                    mSupplierId = data.getStringExtra("supplierId");
                    break;
            }
    }

    /**
     * 监听商品状态是否改变
     */
    interface IChangeGoodsStatus {
        void changeGoodsState(boolean change);
    }

    /**
     * 新增或修改商品
     */
    private void addOrUpdateProduct(String id, String state) {
        if (TextUtils.isEmpty(mEtGoodsFullName.getText().toString())) {
            showShortToast("请输入标题");
            return;
        }
        if (TextUtils.isEmpty(mTvType.getText().toString())) {
            showShortToast("请选择品类");
            return;
        }
        if (TextUtils.isEmpty(mTvMeasureSmallUnit.getText().toString())) {
            showShortToast("请选择计量小单位");
            return;
        }
        if (TextUtils.isEmpty(mTvMainSupplier.getText().toString())) {
            showShortToast("请选择供应商");
            return;
        }
        if (TextUtils.isEmpty(mEtStockSelling.getText().toString())) {
            mBuyPrice = 0;
        } else {
            mBuyPrice = Double.parseDouble(mEtStockSelling.getText().toString());
        }
        if (TextUtils.isEmpty(mEtSystemSelling.getText().toString())) {
            mSysPrice = 0;
        } else {
            mSysPrice = Double.parseDouble(mEtSystemSelling.getText().toString());
        }
        if (TextUtils.isEmpty(mEtWholesaleSelling.getText().toString())) {
            mTradePrice = 0;
        } else {
            mTradePrice = Double.parseDouble(mEtWholesaleSelling.getText().toString());
        }
        if (TextUtils.isEmpty(mEtJoinSelling.getText().toString())) {
            mJoinPrice = 0;
        } else {
            mJoinPrice = Double.parseDouble(mEtJoinSelling.getText().toString());
        }
        if (TextUtils.isEmpty(mEtMemberSelling.getText().toString())) {
            mMemberPrice = 0;
        } else {
            mMemberPrice = Double.parseDouble(mEtMemberSelling.getText().toString());
        }
        if (TextUtils.isEmpty(mEtMemberSelling1.getText().toString())) {
            mMemberPrice1 = 0;
        } else {
            mMemberPrice1 = Double.parseDouble(mEtMemberSelling1.getText().toString());
        }
        if (TextUtils.isEmpty(mEtMemberSelling2.getText().toString())) {
            mMemberPrice2 = 0;
        } else {
            mMemberPrice2 = Double.parseDouble(mEtMemberSelling2.getText().toString());
        }
        if (TextUtils.isEmpty(mEtMemberSelling3.getText().toString())) {
            mMemberPrice3 = 0;
        } else {
            mMemberPrice3 = Double.parseDouble(mEtMemberSelling3.getText().toString());
        }
        if (TextUtils.isEmpty(mEtMemberSelling4.getText().toString())) {
            mMemberPrice4 = 0;
        } else {
            mMemberPrice4 = Double.parseDouble(mEtMemberSelling4.getText().toString());
        }
        if (TextUtils.isEmpty(mEtMemberSelling5.getText().toString())) {
            mMemberPrice5 = 0;
        } else {
            mMemberPrice5 = Double.parseDouble(mEtMemberSelling5.getText().toString());
        }
        if (TextUtils.isEmpty(mEtStockSellingTax.getText().toString())) {
            mStockRate = 0;
        } else {
            mStockRate = Double.parseDouble(mEtStockSellingTax.getText().toString());
        }
        if (TextUtils.isEmpty(mEtSaleTax.getText().toString())) {
            mSaleRate = 0;
        } else {
            mSaleRate = Double.parseDouble(mEtSaleTax.getText().toString());
        }
        mParams = new HashMap<>();
        mParams.put("id", id);
        mParams.put("productCode", mEtSystemCode.getText().toString());
        mParams.put("barcode", mEtMainCode.getText().toString());//条码
        mParams.put("storageCode", mEtStorageCode.getText().toString());//存货编码
        mParams.put("title", mEtGoodsFullName.getText().toString());//标题
        mParams.put("size", mEtSpecification.getText().toString());
        mParams.put("boxBoard", mEtCartonSpecification.getText().toString());
        mParams.put("brandSN", mBrandSN + "");
        mParams.put("supplierId", mSupplierId + "");//供应商
        mParams.put("cityId", "0");
        mParams.put("categorySN", mCategorySN + "");//品类
        mParams.put("bigUnitId", "0");
        mParams.put("subUnitId", mDicSN + "");//计量小单位
        mParams.put("buyPrice", mBuyPrice + "");
        mParams.put("sysPrice", mSysPrice + "");
        mParams.put("tradePrice", mTradePrice + "");
        mParams.put("joinPrice", mJoinPrice + "");
        mParams.put("memberPrice", mMemberPrice + "");
        mParams.put("memberPrice1", mMemberPrice1 + "");
        mParams.put("memberPrice2", mMemberPrice2 + "");
        mParams.put("memberPrice3", mMemberPrice3 + "");
        mParams.put("memberPrice4", mMemberPrice4 + "");
        mParams.put("memberPrice5", mMemberPrice5 + "");
        mParams.put("favorable", mFavorable + "");
        mParams.put("expiry", mExpiry + "");
        mParams.put("expiryUnit", mExpiryUnit + "");
        mParams.put("factory", mEtManufacturer.getText().toString());
        mParams.put("valuationType", mValuationType + "");
        mParams.put("isReturnSale", mIsReturnSale + "");
        mParams.put("isAcceptOrder", mIsAcceptOrder + "");
        mParams.put("inventoryWarning", mEtInventoryWarningDown.getText().toString());
        mParams.put("validityWarning", mEtExpirationDateWarning.getText().toString());
        mParams.put("state", state + "");//上下架状态
        mParams.put("stockRate", mStockRate + "");
        mParams.put("saleRate", mSaleRate + "");
        mParams.put("inventoryWarningMax", mEtInventoryWarningUp.getText().toString());
        mNetProtocol.addOrUpdateProduct(activity, mParams, mFileList, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                showShortToast("修改成功");
                mIChangeGoodsStatus.changeGoodsState(true);
                mGoodsActivity.getSupportFragmentManager().popBackStack();
            }

            @Override
            public void onFail(BaseBean baseBean) {
                showShortToast(baseBean.getMessage());
            }
        });
    }
}
